package com.common.util;

import org.lionsoul.ip2region.DataBlock;
import org.lionsoul.ip2region.DbConfig;
import org.lionsoul.ip2region.DbSearcher;
import org.lionsoul.ip2region.Util;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;

/**
 * @author guochao
 * @version 1.0
 * @date 2022/4/19 22:01
 */
public class IPUtil {


	/**
	 * 获取本地电脑ip地址
	 * @return
	 */
	public static String getLocalIpAddress(){
		InetAddress ip;      //用于获取IP(因为是静态的所以不需要使用new来实例化
		String IP = null;    //用于返回IP
		try {
			ip = Inet4Address.getLocalHost();    //获取IP
			IP = ip.getHostAddress();        	//以字符串形式存储IP
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return IP;
	}


	/**
	 * 获取IP地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if ("0:0:0:0:0:0:0:1".equals(ip)) {
			ip = "127.0.0.1";
		}
		if (ip.split(",").length > 1) {
			ip = ip.split(",")[0];
		}
		return ip;
	}


	/**
	 * 根据IP地址获取城市
	 * @param ip
	 * @return
	 */
	public static String getCityInfo(String ip){
		try {
			URL url = IPUtil.class.getResource("/ip2region.db");
			File file;
			file = new File(url.getPath());
			if (!file.exists()) {
				System.out.println("Error: Invalid ip2region.db file, filePath：" + file.getPath());
				return null;
			}
			//查询算法
			int algorithm = DbSearcher.BTREE_ALGORITHM; //B-tree
			//DbSearcher.BINARY_ALGORITHM //Binary
			//DbSearcher.MEMORY_ALGORITYM //Memory

			DbConfig config = new DbConfig();
			DbSearcher searcher = new DbSearcher(config, file.getPath());
			Method method;
			switch ( algorithm )
			{
				case DbSearcher.BTREE_ALGORITHM:
					method = searcher.getClass().getMethod("btreeSearch", String.class);
					break;
				case DbSearcher.BINARY_ALGORITHM:
					method = searcher.getClass().getMethod("binarySearch", String.class);
					break;
				case DbSearcher.MEMORY_ALGORITYM:
					method = searcher.getClass().getMethod("memorySearch", String.class);
					break;
				default:
					return null;
			}
			DataBlock dataBlock;
			if (!Util.isIpAddress(ip)) {
				System.out.println("Error: Invalid ip address");
				return null;
			}
			dataBlock  = (DataBlock) method.invoke(searcher, ip);
			return dataBlock.getRegion();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/*public static void main(String[] args) {
		String detail = getCityInfo("113.118.149.64");
		System.out.println(detail);
	}*/

}

